package com.zk.iotgateway.netty.coder.workcard;

import com.zk.iotgateway.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * 定位器解码器
 * 粘包分包  359339075404841
 * @author:mn.m
 * @create 2019-04-19 下午 02:27
 **/
@Component
@Scope("prototype")
public class LocatorDecoder extends ByteToMessageDecoder {

   /*
   * 协议基本长度 起始位2byte +包长度1byte +协议号1byte +结束位2byte
   * */
   public final int BASE_LENGTH =6;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("网关--"+channelHandlerContext.channel().localAddress());
        int len = byteBuf.readableBytes();
        //数据包可读长度必须大于基本长度
        if (len >=BASE_LENGTH){
            /*读取数据*/
            byte[] dist=new byte[len];
            byteBuf.readBytes(dist);
            System.out.println("content:"+ StringUtils.byte2HexStr(dist));
            String str = StringUtils.encodeHex(dist).trim();
            System.out.println("readable str length is "+str.length());
            String res =StringUtils.getPacket(str);
            System.out.println("匹配结果为-----"+res);
            if (res!=null){
                list.add(res);
            }else {
                return;
            }

        }
    }
}
